package com.ag.score.apiservice;

import com.ag.common.tools.DateUtil;
import com.ag.score.entity.TRecord;
import com.ag.score.entity.TUser;
import com.ag.score.mapper.TRecordMapper;
import com.ag.score.mapper.TUserMapper;
import com.ag.score.util.MinuteParam;
import com.ag.score.util.ScoreParam;
import com.alibaba.fastjson.JSONObject;
import com.redis.RedisKit;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 *  接口服务类
 */
@Service
public class AppService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AppService.class);
    @Autowired(required = false)
    private TUserMapper tUserMapper;
    @Autowired(required = false)
    private TRecordMapper tRecordMapper;
    /**
     * 登录
     * @param paramJson
     */
    public boolean userLogin(JSONObject paramJson){
        String username = paramJson.getString("username");
        String pass = paramJson.getString("pass");
        TUser user = tUserMapper.getTUserByUserName(username);
        if(user == null ){
            return false;
        }
        String password  = new String(DigestUtils.md5Hex(pass));
        if(!password.equals(user.getPass())){
            return false;
        }
        String sessionid = UUID.randomUUID().toString();
        user.setToken(sessionid);
        user.setPass("");
        RedisKit.set(sessionid,JSONObject.toJSON(user).toString());
        paramJson.put("resultStr",JSONObject.toJSON(user));

        return true;
    }

    /**
     * 添加记录
     * @param paramJson
     * @return
     */
    public boolean addRecord(JSONObject paramJson){
        //
        String dataval = RedisKit.getString(ScoreParam.dataRedisKey);
        if(dataval == null){
            paramJson.put("resultStr","系统错误");
            return false;
        }
        int hour = DateUtil.getHour();
        if(hour< MinuteParam.startHour || hour>MinuteParam.endHour){
            paramJson.put("resultStr","不在时间要求内");
            return false;
        }
        //当前值
        double data = new Double(dataval);

        String token = paramJson.getString("token");
        String val = RedisKit.getString(token);
        if(val == null){
            paramJson.put("resultStr","请登录");
            return false;
        }
        JSONObject userJson = JSONObject.parseObject(val);
        int uid = userJson.getInteger("id");
        int score = paramJson.getInteger("score");
        int type = paramJson.getInteger("type");
        if(MinuteParam.getScoreValFromScoreMap(score+"") == null){
            paramJson.put("resultStr","错误的积分");
            return false;
        }
        if(type !=1 && type !=-1){
            paramJson.put("resultStr","涨跌类型不对");
            return false;
        }
        int minute = paramJson.getInteger("minute");
        if(MinuteParam.getMinuteValFromMinuteMap(minute+"") == null){
            paramJson.put("resultStr","错误的分钟");
            return false;
        }
        Date date = new Date();
        String createTime = DateUtil.date2String(date,"");
        String endH = DateUtil.date2String(DateUtil.minusMinutes(date,-minute),"HH");
        if(new Integer(endH)>=MinuteParam.endHour){
            paramJson.put("resultStr","错误的分钟,超过要求");
            return false;
        }

        TUser user = tUserMapper.selectById(uid);
        if(user.getScore()<score){
            paramJson.put("resultStr","账号积分不足");
            return false;
        }

        String cacheRecord = RedisKit.getString("addRecord_"+uid);
        if(cacheRecord !=null){
            paramJson.put("resultStr","请控制频次，1分钟只能操作一次");
            return false;
        }

        //添加记录
        TRecord record = new TRecord();
        record.setRecordtype(MinuteParam.recordType);
        record.setStartdata(data);
        record.setEnddata(0);
        record.setStatus(0);
        record.setType(type);
        record.setUsescore(score);
        record.setResscore(0);
        record.setUid(uid);
        record.setMinute(minute);
        record.setWinlv(MinuteParam.getMinuteValFromMinuteMap(minute+""));
        record.setCretetime(createTime);
        record.setEndtime(DateUtil.date2String(DateUtil.minusMinutes(date,-minute),"HH:mm"));
        tRecordMapper.insert(record);
        //更新积分
        user.setScore(user.getScore() - score);
        tUserMapper.updateById(user);

        paramJson.put("resultStr","提交成功");

        return true;
    }

    /**
     * 记录集合
     * @param paramJson
     * @return
     */
    public boolean recordPage(JSONObject paramJson){
        String dataval = RedisKit.getString(ScoreParam.dataRedisKey);
        if(dataval == null){
            paramJson.put("resultStr","系统错误");
            return false;
        }

        //当前值
        double data = new Double(dataval);

        String token = paramJson.getString("token");
        String val = RedisKit.getString(token);
        if(val == null){
            paramJson.put("resultStr","请登录");
            return false;
        }
        HashMap<String,Object> param = new  HashMap<String,Object>();
        JSONObject userJson = JSONObject.parseObject(val);
        int uid = userJson.getInteger("id");
        param.put("uid",uid);
        int status = paramJson.getInteger("status");
        param.put("status",status);
        param.put("recordtype",MinuteParam.recordType);
        if(status == 1){
            int pageNo = 0 ;
            int pageSize = 10;
            if(paramJson.get("pageNo")!=null){
                pageNo = paramJson.getInteger("pageNo");
            }
            param.put("start",pageNo*pageSize);
            param.put("size",pageSize);
        }
        List<TRecord> list = tRecordMapper.queryPage(param);


        if(status == 0){
            for(int i=0;i<list.size();i++){
                list.get(i).setEnddata(data);
            }

        }
        paramJson.put("resultStr",list);
        return true;
    }

    /**
     * 参数
     * @return
     */
    public JSONObject queryParam(){
        JSONObject resJson = new JSONObject();

        resJson.put("score",MinuteParam.getScoreMap());

        resJson.put("minute",MinuteParam.getMinuteMap());

        return resJson;
    }
}
